<template>
  <div class="login-container">
    <div class="wrapper">
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules">
        <h1>考勤系统登录</h1>
        <div class="input-box" :class="{ 'active': loginForm.account }">
          <el-input 
            v-model="loginForm.account" 
            class="transparent-input"
            :prefix-icon="User"
            size="large"
            placeholder=" "
            required
          />
          <label>员工号/电话/邮箱</label>
        </div>
        <div class="input-box" :class="{ 'active': loginForm.password }">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            class="transparent-input" 
            :prefix-icon="Lock"
            size="large" 
            show-password 
            placeholder=" "
            @keyup.enter="handleLogin"
            required
          />
          <label>密码</label>
        </div>

        <div class="row">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <a href="javascript:void(0)" @click="forgotPassword">忘记密码?</a>
        </div>

        <el-button 
          :loading="loading" 
          class="btn" 
          @click="handleLogin"
        >
          登 录
        </el-button>

        <div class="signup-link">
          <p>还没有账号? <a @click="goToRegister">立即注册</a></p>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { login } from '@/api/login'

const router = useRouter()
const name = ref('')
const employeeId = ref('')
const employeeNo = ref('')
const isAdmin = ref(false)
const loading = ref(false)
const loginFormRef = ref(null)

const loginForm = reactive({
  account: '',
  password: '',
  remember: false,
})

const loginRules = {
  account: [{ required: true, message: '请输入手机号、邮箱或员工编号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
}

// 处理登录
const handleLogin = () => {
  if (!loginFormRef.value) return
  
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await login(loginForm)
        if (res.data.success) {
          // 先存储数据
          name.value = res.data.name
          employeeId.value = res.data.employeeId
          employeeNo.value = res.data.employeeNo
          isAdmin.value = res.data.isAdmin

          // 存储到localStorage
          localStorage.setItem('name', name.value)
          localStorage.setItem('employeeId', employeeId.value)
          localStorage.setItem('employeeNo', employeeNo.value)
          localStorage.setItem('isAdmin', isAdmin.value)
          localStorage.setItem('token', 'Bearer ' + res.data.token)

          // 显示成功消息
          ElMessage.success(res.data.message || '登录成功')
          
          // 使用 replace 替换路由历史，防止返回登录页
          router.replace({ name: 'Dashboard' }).catch(err => {
            console.error('路由跳转错误:', err)
            // 如果导航失败，尝试直接替换到路径
            router.replace('/dashboard')
          })
        } else {
          ElMessage.error('账号或密码错误')
        }
      } catch (error) {
        console.error('登录错误:', error)
        if (error.code === 'ERR_NETWORK') {
          ElMessage.error('网络连接失败，请检查后端服务是否启动')
        } else if (error.response?.status === 401) {
          ElMessage.error('账号或密码错误')
        } else {
          ElMessage.error('登录失败，请稍后重试')
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 添加忘记密码功能
const forgotPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}

// 如果之前记住了账号，自动填充
onMounted(() => {
  const rememberedAccount = localStorage.getItem('rememberedAccount')
  if (rememberedAccount) {
    loginForm.account = rememberedAccount
    loginForm.remember = true
  }
})
</script>

<style scoped>
* {
  font-family: "Poppins", sans-serif, "微软雅黑", "黑体";
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.login-container {
  height: 100vh;
  width: 100vw;
  background-image: url('@/assets/login-bg.jpg');
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 1;
}

.wrapper {
  position: relative;
  width: 400px;
  height: 450px;
  background: rgba(255, 255, 255, 0.1);
  border: 2px solid rgba(255, 255, 255, 0.5);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  z-index: 2;
}
  
.wrapper:hover {
  box-shadow: 0 0 40px rgba(255, 255, 255, 0.5);
  transition: all 0.3s ease;
}

.wrapper h1 {
  font-size: 2em;
  color: #fff;
  text-align: center;
  margin-bottom: 20px;
}

.wrapper .input-box {
  position: relative;
  width: 310px;
  margin: 30px 0;
  border-bottom: 2px solid #fff;
}

.wrapper .input-box :deep(.el-input__wrapper) {
  background: transparent;
  box-shadow: none;
  padding: 0;
}

.wrapper .input-box :deep(.el-input__inner) {
  height: 50px;
  background: transparent;
  outline: none;
  border: none;
  font-size: 1em;
  color: #fff !important;
  padding: 0 40px 0 5px;
}

/* 调整Element Plus内置图标的样式 */
.wrapper .input-box :deep(.el-input__prefix) {
  color: #fff;
}

.wrapper .input-box label {
  position: absolute;
  top: 50%;
  left: 35px;
  transform: translateY(-50%);
  font-size: 1em;
  color: #fff;
  pointer-events: none;
  transition: 0.5s;
  z-index: 1;
}

/* 输入框获得焦点或有内容时的标签移动效果 */
.wrapper .input-box.active label,
.wrapper .input-box :deep(.el-input__inner:focus) ~ label {
  top: -5px;
  left: 5px;
  font-size: 0.9em;
}

/* 设置placeholder为空格，保持隐藏状态 */
.wrapper .input-box :deep(.el-input__inner::placeholder) {
  color: transparent;
}

.wrapper .row {
  margin: -15px 0 15px;
  font-size: 0.9em;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .row :deep(.el-checkbox__label) {
  color: #fff;
}

.wrapper .row a {
  color: #fff;
  text-decoration: none;
}

.wrapper .row a:hover {
  text-decoration: underline;
}

.wrapper .btn {
  width: 100%;
  height: 40px;
  background: #fff;
  outline: none;
  border: none;
  border-radius: 40px;
  cursor: pointer;
  font-size: 1em;
  font-weight: 500;
  color: #000;
  margin-top: 10px;
}
  
.wrapper .btn:hover {
  background: #ffffea;
  color: #000;
}

.wrapper .signup-link {
  font-size: 0.9em;
  color: #fff;
  text-align: center;
  margin: 25px 0 10px;
}

.wrapper .signup-link a {
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  cursor: pointer;
}

.wrapper .signup-link a:hover {
  text-decoration: underline;
}

@media (max-width: 360px) {
  .wrapper {
    width: 100%;
    height: 100vh;
    border: none;
    border-radius: 0px;
  }

  .wrapper .input-box {
    width: 290px;
  }
}

/* 确保checkbox显示正确 */
.wrapper .row :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #fff;
}

.wrapper .row :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #fff;
  border-color: #fff;
}

.wrapper .row :deep(.el-checkbox__inner::after) {
  border-color: rgba(62, 64, 77, 1);
}
</style>
